<!-- templates/editor.html -->
{% extends "base.html" %}
{% block title %}代码编辑器{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/styles/default.min.css">
<style>
    .main-content {
        padding-left: 60px;
    }
    .task-sidebar {
        background: rgb(206, 206, 206)!important;
        border-radius: 24px !important;
        margin: 20px 0;
        padding: 1.2rem;
        margin-bottom: 1.5rem;
        color: #000000;
        font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        min-width: 320px;
        flex: 0 0 auto;
    }

    .task-card {
        background: rgb(232, 231, 231)!important;
        border-radius: 18px !important;
        overflow: hidden;
    }

    .task-card .card-title {
        color: #000000 !important;
        font-family: 'Helvetica Neue', Arial, sans-serif;
        font-weight: 600;
        font-size: 1.1rem;
        margin-bottom: 0.8rem;
    }

    .task-card .card-text {
        color: #000000 !important;
        font-family: 'Microsoft YaHei', sans-serif;
        font-size: 0.95rem;
        line-height: 1.5;
    }

    .task-deadline {
        color: #3ce76a !important;
        font-family: 'Arial', sans-serif;
    }

    .task-card:hover {
        background: rgba(255,255,255,0.1);
        transform: translateY(-3px) scale(1.02);
    }

    #editor { 
        background: rgb(255, 255, 255)!important;
        backdrop-filter: blur(8px);
        border-radius: 24px !important;
        border: 1px solid rgba(99, 102, 241, 0.3);
        color: #000000 !important;
        height: 60vh;
        min-height: 400px;
        font-size: 24px;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        margin-bottom: 1.5rem;
    }

    .example-panel {
        border-radius: 24px !important;
        background: rgb(206, 206, 206)!important;
        border: 1px solid #dee2e6;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .analysis-panel {
        background: rgb(206, 206, 206)!important;
        border: 1px solid #dee2e6;
        border-radius: 24px !important;
        padding: 1.5rem;
    }

    pre.example-code {
        position: relative;
        background:rgb(255, 255, 255)!important;
        color: #000000;
        padding: 1.5rem;
        border-radius: 6px;
        margin: 1rem 0;
    }

    .copy-button {
        background:rgb(206, 206, 206)!important;
        position: absolute;
        right: 1rem;
        top: 1rem;
        opacity: 0.7;
        transition: all 0.3s ease;
        padding: 0.2rem 0.6rem;
        font-size: 0.9rem;
        white-space: nowrap;
        line-height: 1.2;
        height: 2rem;
        min-width: 2rem;
    }

    .copy-button:hover {
        opacity: 1;
        transform: scale(1.05);
    }

    .problem-list {
        max-height: 50vh;
        overflow-y: auto;
        padding-right: 0.5rem;
    }

    .error-card {
        border-left: 4px solid #dc3545;
        transition: transform 0.3s ease;
        margin-bottom: 1rem;
    }

    .error-card:hover {
        transform: translateX(5px);
    }

    .task-history-card {
        background: rgba(255, 255, 255, 0.9) !important;
        border-radius: 12px !important;
        transition: all 0.2s ease;
        margin-bottom: 0.5rem;
    }

    .task-history-card:hover {
        transform: translateX(5px);
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    #taskHistoryList::-webkit-scrollbar {
        width: 6px;
    }

    #taskHistoryList::-webkit-scrollbar-track {
        background: rgba(0,0,0,0.1);
        border-radius: 4px;
    }

    #taskHistoryList::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 4px;
    }

    .task-history-container h6 {
        font-weight: 600;
        margin-bottom: 15px;
        color: #444;
    }

    #taskModal .modal-dialog {
        max-width: 1200px;
        width: 90%;
        min-height: 600px;
        margin: 1.75rem auto;
    }

    #taskModal .modal-content {
        height: 85vh;
        display: flex;
        flex-direction: column;
        border-radius: 24px;
    }

    #taskModal .modal-body {
        flex: 1;
        overflow-y: auto;
        padding: 25px;
    }

    #taskModal .modal-header {
        padding: 20px;
        border-bottom: 2px solid #dee2e6;
    }

    .task-history-container {
        margin-top: 25px;
        border-top: 1px solid #eee;
        padding-top: 20px;
        max-height: 600px;
        overflow-y: auto;
    }
    @media (max-width: 768px) {
        #taskModal .modal-dialog {
            width: 95%;
            min-height: 400px;
        }
        #taskModal .modal-content {
            height: 90vh;
        }
        #taskModal .modal-body {
            padding: 15px;
        }
        .task-history-container {
            max-height: 200px;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <!-- 任务侧边栏 -->
        <div class="col-md-4 col-lg-3 task-sidebar">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5><i class="fas fa-tasks me-2"></i>班级任务</h5>
                <button class="btn btn-sm btn-outline-secondary" onclick="refreshTasks()">
                    <i class="fas fa-sync"></i>
                </button>
            </div>
            <div id="taskList"></div>

            <div class="mt-4">
                <h6><i class="fas fa-history me-2"></i>任务提交历史</h6>
                <div id="taskHistoryList" class="mt-2" style="max-height: 40vh; overflow-y: auto;">
                    <div class="text-muted small" id="historyPlaceholder">选择任务查看历史记录</div>
                </div>
            </div>
        </div>

        <!-- 主编辑器区域 -->
        <div class="col-md-8 col-lg-9 main-content">
            <div class="row mb-3">
                <div class="col">
                    <button class="btn btn-primary btn-lg" onclick="analyzeCode()">
                        <i class="fas fa-play me-2"></i>运行代码检查
                    </button>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div id="editor"></div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="example-panel">
                        <h4 class="mb-3">
                            <i class="fas fa-code me-2"></i>
                            示例代码建议
                        </h4>
                        <div id="example-code"></div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="analysis-panel">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h4 class="m-0">
                                <i class="fas fa-bug me-2"></i>
                                代码检测结果
                            </h4>
                            <div class="score-display">
                                <span class="badge bg-primary fs-5">
                                    评分: <span id="scoreValue">0.0</span>/10
                                </span>
                            </div>
                        </div>
                        <div id="analysis-results" class="problem-list"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="taskModal">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="taskTitle"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-8">
                            <div id="taskContent" class="mb-3"></div>
                            <div class="text-muted small">
                                <i class="fas fa-clock"></i> 发布时间：
                                <span id="taskCreatedAt"></span>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="alert alert-danger mb-4">
                                <i class="fas fa-exclamation-circle"></i> 截止时间：
                                <span id="taskDeadline"></span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 新增历史记录容器 -->
                    <div class="task-history-container">
                        <h6><i class="fas fa-history me-2"></i>提交历史</h6>
                        <div id="taskHistoryContent"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/mode-python.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/languages/python.min.js"></script>

<script>
    const editor = ace.edit("editor");
    editor.setTheme("ace/theme/chrome");
    editor.session.setMode("ace/mode/python");
    editor.session.setUseWrapMode(true);
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableLiveAutocompletion: true
    });
    editor.setValue(`# 欢迎使用CodeMaster 在这里编写你的代码`);

    let currentTaskId = null;

    async function loadTasks() {
        try {
            const response = await fetch('/api/student/tasks');
            const tasks = await response.json();
            renderTasks(tasks);
        } catch (error) {
            console.error('加载任务失败:', error);
        }
    }

    function renderTasks(tasks) {
        const container = document.getElementById('taskList');
        container.innerHTML = tasks.map(task => `
            <div class="card task-card mb-2" onclick="showTaskDetail(${task.id})">
                <div class="card-body p-3">
                    <h6 class="card-title mb-2">${task.title}</h6>
                    <p class="card-text text-muted small mb-2">
                        ${task.content.substring(0, 30)}${task.content.length > 30 ? '...' : ''}
                    </p>
                    <div class="task-deadline small">
                        <i class="fas fa-clock"></i> 
                        ${new Date(task.deadline).toLocaleDateString()}
                    </div>
                </div>
            </div>
        `).join('');
    }

    async function showTaskDetail(taskId) {
    currentTaskId = taskId;
    const loadingToast = new bootstrap.Toast(document.getElementById('loadingToast'));
    
    try {
        loadingToast.show();

        // 独立请求任务详情
        const taskResponse = await fetch(`/api/tasks/${taskId}`);
        if (!taskResponse.ok) {
            throw new Error(`任务加载失败: ${taskResponse.status}`);
        }
        const task = await taskResponse.json();

        // 更新模态框内容
        document.getElementById('taskTitle').textContent = task.title;
        document.getElementById('taskContent').innerHTML = task.content.replace(/\n/g, '<br>');
        document.getElementById('taskCreatedAt').textContent = new Date(task.created_at).toLocaleString();
        document.getElementById('taskDeadline').textContent = new Date(task.deadline).toLocaleString();

        // 独立加载历史记录
        try {
            const historyResponse = await fetch(`/api/tasks/${taskId}/histories`);
            if (historyResponse.ok) {
                const histories = await historyResponse.json();
                renderTaskHistory(histories, document.getElementById('taskHistoryContent'));
            }
        } catch (historyError) {
            console.warn('历史记录加载异常:', historyError);
        }

        new bootstrap.Modal(document.getElementById('taskModal')).show();

    } catch (error) {
        alert(`操作失败: ${error.message}`);
    } finally {
        loadingToast.hide();
    }
}


    function renderTaskHistory(histories, container) {
    container.innerHTML = histories.length === 0 ? 
        '<div class="text-muted small">该任务暂无提交记录</div>' :
        histories.map(history => `
            <div class="card mb-2 task-history-card">
                <div class="card-body p-2">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="flex-grow-1">
                            <small class="text-muted">${history.timestamp}</small>
                            <div class="text-truncate">${history.preview}</div>
                        </div>
                        <span class="badge ${getScoreBadgeClass(history.score)} ms-2">
                            ${history.score.toFixed(1)}
                        </span>
                    </div>
                </div>
            </div>
        `).join('');
}

    function getScoreBadgeClass(score) {
        if (score >= 8) return 'bg-success';
        if (score >= 5) return 'bg-warning';
        return 'bg-danger';
    }

    async function analyzeCode() {
    if (!currentTaskId) {
        alert('请先选择任务');
        return;
    }

    const code = editor.getValue();
    const params = new URLSearchParams();
    params.append('code', code);
    params.append('task_id', currentTaskId);
    
    try {
        // 主分析请求
        const response = await fetch('/analyze', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params
        });

        // 检查HTTP状态码
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || `服务器返回错误状态码: ${response.status}`);
        }

        // 解析响应数据
        const data = await response.json();
        renderAnalysis(data);

        // 独立处理历史记录请求
        try {
            const historyResponse = await fetch(`/api/tasks/${currentTaskId}/histories`);
            if (!historyResponse.ok) {
                console.warn('历史记录加载失败:', historyResponse.status);
                return;
            }
            const histories = await historyResponse.json();
            renderTaskHistory(histories);
        } catch (historyError) {
            console.error('历史记录请求异常:', historyError);
        }

    } catch (error) {
        // 精准错误提示
        const errorMessage = error.message.includes('Failed to fetch') 
            ? '网络连接异常，请检查网络后重试' 
            : error.message;
        
        alert(`分析失败: ${errorMessage}`);
        console.error('详细错误:', error);
    }
}

    function renderAnalysis(data) {
        const resultsContainer = document.getElementById('analysis-results');
        const exampleContainer = document.getElementById('example-code');
        
        resultsContainer.innerHTML = '';
        exampleContainer.innerHTML = '';
        updateScoreDisplay(data.score);

        if (data.pylint) {
            renderPylintResults(data, resultsContainer);
        }

        if (data.ai_feedback) {
            processAIFeedback(data.ai_feedback, resultsContainer, exampleContainer);
        }
    }

    function updateScoreDisplay(score) {
        const scoreElement = document.getElementById('scoreValue');
        if (!score) return;

        scoreElement.textContent = score.toFixed(1);
        const badge = scoreElement.parentElement;
        badge.classList.remove('bg-success', 'bg-warning', 'bg-danger');
        
        if (score >= 8) {
            badge.classList.add('bg-success');
        } else if (score >= 5) {
            badge.classList.add('bg-warning');
        } else {
            badge.classList.add('bg-danger');
        }
    }

    function renderPylintResults(data, container) {
        const specialCharMatch = data.pylint.match(/检测到特殊字符：(.*)/);
        if (specialCharMatch) {
            const alertDiv = document.createElement('div');
            alertDiv.className = 'alert alert-warning';
            alertDiv.innerHTML = `
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        发现特殊字符：${specialCharMatch[1]}
                    </div>
                    <button class="btn btn-sm btn-outline-primary" 
                            onclick="cleanSpecialCharacters()">
                        自动清理
                    </button>
                </div>
            `;
            container.appendChild(alertDiv);
        }

        const lineNumbers = extractErrorLines(data.pylint);
        lineNumbers.forEach(line => {
            const card = document.createElement('div');
            card.className = 'card error-card';
            card.innerHTML = `
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="mb-1">
                                <i class="fas fa-times-circle text-danger me-2"></i>
                                第 ${line} 行发现问题
                            </h5>
                            <p class="mb-0 text-muted">${getErrorDescription(data.pylint, line)}</p>
                        </div>
                        <button class="btn btn-link" 
                                onclick="editor.gotoLine(${line}, 0, true)">
                            <i class="fas fa-arrow-right"></i>
                        </button>
                    </div>
                </div>
            `;
            container.appendChild(card);
        });
    }

    function processAIFeedback(feedback, resultsContainer, exampleContainer) {
        const { textFeedback, exampleCode } = parseAIFeedback(feedback);

        if (textFeedback) {
            const feedbackDiv = document.createElement('div');
            feedbackDiv.className = 'card mt-3 border-primary';
            feedbackDiv.innerHTML = `
                <div class="card-header bg-primary text-white">
                    <i class="fas fa-comment-dots me-2"></i>AI 建议
                </div>
                <div class="card-body">
                    ${textFeedback.replace(/\n/g, '<br>')}
                </div>
            `;
            resultsContainer.appendChild(feedbackDiv);
        }

        if (exampleCode) {
            const exampleDiv = document.createElement('div');
            exampleDiv.innerHTML = `
                <pre class="example-code">
                    <button class="btn btn-light copy-button" 
                            onclick="copyExampleCode(this)">
                        <i class="fas fa-copy"></i>
                    </button>
                    ${hljs.highlight(exampleCode, { language: 'python' }).value}
                </pre>
            `;
            exampleContainer.appendChild(exampleDiv);
        }
    }

    function parseAIFeedback(feedback) {
        const exampleStart = feedback.indexOf('正确示例:');
        if (exampleStart === -1) {
            return { textFeedback: cleanPrefix(feedback) };
        }

        const rawTextFeedback = feedback.slice(0, exampleStart).trim();
        const exampleCode = feedback.slice(exampleStart + 5).trim();
        return { textFeedback: cleanPrefix(rawTextFeedback), exampleCode };
    }

    function cleanPrefix(text) {
        return text.replace(/^\s*\d+\.\s*/, '');
    }

    function copyExampleCode(button) {
        const preElement = button.parentElement;
        const code = preElement.textContent.replace('复制', '').trim();
        
        navigator.clipboard.writeText(code).then(() => {
            button.innerHTML = '<i class="fas fa-check"></i>';
            setTimeout(() => {
                button.innerHTML = '<i class="fas fa-copy"></i>';
            }, 2000);
        });
    }

    function getErrorDescription(pylintOutput, line) {
        const pattern = new RegExp(`temp.py:${line}:(.*?)(\\n|$)`);
        const match = pylintOutput.match(pattern);
        return match ? match[1].trim() : '代码逻辑问题';
    }

    function extractErrorLines(pylintOutput) {
        const errors = pylintOutput.match(/temp.py:(\d+):/g) || [];
        return [...new Set(errors.map(e => parseInt(e.match(/\d+/)[0])))]
    }

    function cleanSpecialCharacters() {
        const cleanedCode = editor.getValue()
            .replace(/\r/g, '')
            .replace(/[\x00-\x1F\x7F]/g, '')
            .replace(/\u2028|\u2029/g, '');
        editor.setValue(cleanedCode);
        analyzeCode();
    }

    document.addEventListener('DOMContentLoaded', loadTasks);
</script>
{% endblock %}